//
//  MenuController.m
//  Cook
//
//  Created by Macbookpro on 15/4/15.
//  Copyright (c) 2015年 dingjun. All rights reserved.
//

#import "MenuController.h"
#import "DetailController.h"
#import "MyConnection.h"
#import "UIImageView+WebCache.h"
#import "UIScrollView+PullLoad.h"
#import "ResultCollectionViewCell.h"
#import "VegetableMenu.h"

@interface MenuController ()<UICollectionViewDataSource, UICollectionViewDelegate, PullDelegate>
{
    CGAdapter _myAd;
}
@property (nonatomic, retain) NSMutableArray *dataArray;
@property (nonatomic, retain) UICollectionView *collection;
@end

@implementation MenuController
- (void)dealloc
{
    [_dataArray release];
    [_collection release];
    [_title1 release];
    [_title2 release];
    
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.dataArray = [NSMutableArray array];
        _myAd = [AdapterModel getCGAdapter];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self creatBackGround];
    [self creatCollection];
//    [self getConnect];
}

- (void)creatBackGround
{
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, self.view.frame.size.height - 50)];
    [imageView setImage:[UIImage imageNamed:@"classifyPhoto1.png"]];
    [self.view addSubview:imageView];
    [imageView release];
    
}

//// 用来判断是上拉加载还是下啦刷新, state为当前加载状态
//- (void)scrollView:(UIScrollView *)scrollView loadWithState:(LoadState)state
//{
//    
//    NSLog(@"%u",state);
//    if (state == PullDownLoadState) {
//        
//        [self getConnect];
//        
//    } else {
//        
//        [self loadMore];
//    }
//}
////上拉加载
//- (void)loadMore
//{
//    self.count++;
//    NSMutableDictionary *dicP = [NSMutableDictionary dictionary];
//    [dicP setObject:@"0" forKey:@"phonetype"];
//    [dicP setObject:[NSString stringWithFormat:@"%ld", self.idNumber] forKeyedSubscript:@"catalog_id"];
//    [dicP setObject:@"8" forKey:@"pageRecord"];
//    [dicP setObject:@"0" forKey:@"is_traditional"];
//    [dicP setObject:@"" forKey:@"user_id"];
//    [dicP setObject:[NSString stringWithFormat:@"%ld", self.count] forKey:@"page"];
//    
//    __block MenuController *my = self;
//    __block UICollectionView *myCollection = self.collection;
//    
//    [MyConnection connectWithUrl:@"http://121.41.84.91/HandheldKitchen/api/vegetable/tblvegetable!getInfo.do" parmaters:dicP finishBlock:^(NSData *data) {
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//        NSArray *array = [dic objectForKey:@"data"];
//        [my.dataArray addObjectsFromArray:array];
//        [myCollection reloadData];
//        [myCollection stopLoadWithState:PullUpLoadState];
//        
//    }];
//
//}
//
//// 下拉刷新
//-(void)getConnect
//{
//    NSMutableDictionary *dicP = [NSMutableDictionary dictionary];
//    [dicP setObject:@"0" forKey:@"phonetype"];
//    [dicP setObject:[NSString stringWithFormat:@"%ld", self.idNumber] forKeyedSubscript:@"catalog_id"];
//    [dicP setObject:@"1" forKey:@"page"];
//    [dicP setObject:@"8" forKey:@"pageRecord"];
//    [dicP setObject:@"0" forKey:@"is_traditional"];
//    [dicP setObject:@"" forKey:@"user_id"];
//    self.count = 1;
//    [self.dataArray removeAllObjects];
//    
//    __block MenuController *my = self;
//    __block UICollectionView *myCollection = self.collection;
//    
//    [MyConnection connectWithUrl:@"http://121.41.84.91/HandheldKitchen/api/vegetable/tblvegetable!getInfo.do" parmaters:dicP finishBlock:^(NSData *data) {
//        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//        NSArray *array = [dic objectForKey:@"data"];
//        [my.dataArray addObjectsFromArray:array];
//        
//        [myCollection reloadData];
//        [myCollection stopLoadWithState:PullDownLoadState];
//    }];
//    
//}


- (void)creatCollection
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10 * _myAd.sWidth, 64 + 10, self.view.frame.size.width - 10 * _myAd.sWidth, 30 * _myAd.sHeight)];
    label.text = [NSString stringWithFormat:@"%@->%@", _title1, _title2];
    label.textColor = [UIColor whiteColor];
    [self.view addSubview:label];
    [label release];
    
    UICollectionViewFlowLayout *myLayout = [[UICollectionViewFlowLayout alloc] init];
    
    myLayout.itemSize = CGSizeMake(self.view.frame.size.width *0.5 - 20, 140 * _myAd.sHeight);
    myLayout.minimumInteritemSpacing = 10.0f;
    myLayout.minimumLineSpacing = 20.0f;
    myLayout.sectionInset = UIEdgeInsetsMake(5, 0, 20, 20);
    myLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64 + 10 + label.frame.size.height + 10, self.view.frame.size.width, self.view.frame.size.height - 114 * _myAd.sHeight) collectionViewLayout:myLayout];
    [_collection registerClass:[ResultCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    _collection.backgroundColor = [UIColor clearColor];
    
    _collection.dataSource = self;
    _collection.delegate = self;
    
    // 设置代理人
    _collection.pullDelegate = self;
    // 允许程序上拉加载下拉刷新
//    _collection.canPullDown = YES;
    _collection.canPullUp = YES;
    
    [self.view addSubview:_collection];
    [_collection reloadData];
    [_collection release];
    [myLayout release];
    
    [self scrollView:[[[UIScrollView alloc] init] autorelease] loadWithState:PullUpLoadState];
}

- (void)scrollView:(UIScrollView *)scrollView loadWithState:(LoadState)state
{
    self.count++;
    NSString *numTag = nil;
    for (NSString *num in self.dataArray) {
        if (numTag == nil) {
            numTag = num;
        }
        else {
            numTag = [NSString stringWithFormat:@"%@, %@", numTag, num];
        }
    }
    
    if (state == PullUpLoadState) {
        [self startConnect];
    }
    
}

- (void)startConnect
{
    
    self.navigationController.navigationBar.hidden = YES;
    NSMutableDictionary *dicP = [NSMutableDictionary dictionary];
    [dicP setObject:@"0" forKey:@"phonetype"];
    [dicP setObject:[NSString stringWithFormat:@"%ld", self.idNumber] forKeyedSubscript:@"catalog_id"];
    [dicP setObject:@"8" forKey:@"pageRecord"];
    [dicP setObject:@"0" forKey:@"is_traditional"];
    [dicP setObject:@"" forKey:@"user_id"];
    [dicP setObject:[NSString stringWithFormat:@"%ld", self.count] forKey:@"page"];
    
    __block MenuController *my = self;
    __block UICollectionView *myCollection = self.collection;
    [MyConnection connectWithUrl:@"http://121.41.84.91/HandheldKitchen/api/vegetable/tblvegetable!getInfo.do" parmaters:dicP finishBlock:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = [dic objectForKey:@"data"];
        
            [my.dataArray addObjectsFromArray:array];
            [myCollection reloadData];
            [myCollection stopLoadWithState:PullUpLoadState];
         my.navigationController.navigationBar.hidden = NO;
        if (array.count == 0)
        {
                UIAlertView *view = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"没有更多的内容了" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [view show];
                [view release];
                [myCollection setCanPullUp:NO];
                my.navigationController.navigationBar.hidden = NO;
            }
        
    }];

}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = [_dataArray objectAtIndex:indexPath.item];
    ResultCollectionViewCell *cell = [_collection dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"imagePlace" ofType:@"jpg"];
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    [cell.foodImageView sd_setImageWithURL:[dic objectForKey:@"imagePathLandscape"] placeholderImage:image];
    [cell.foodNameLabel setText:[dic objectForKey:@"name"]];
    [cell.clickLabel setText:[NSString stringWithFormat:@"❤️ %@", [dic objectForKey:@"clickCount"]]];
    NSLog(@"%@", cell);
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DetailController *detail = [[[DetailController alloc] init] autorelease];
    NSDictionary *dic = [self.dataArray objectAtIndex:indexPath.item];
    detail.vegetableMenuModel.vegetable_id = dic[@"vegetable_id"];
    self.navigationController.navigationBar.hidden = NO;
    [self.navigationController pushViewController:detail animated:YES];

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
